package nsu.grandfinal;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.StrictMode;
import android.util.Log;

public class NaverParser {
	String							key1	= "3a2b15266e6879020917091f85a4bc98";
	ArrayList<XmlData>	m_xmlData;
	
	public NaverParser() {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
	}
	
	public ArrayList<XmlData> GetXmlData(String searchTxt, int count) {
		m_xmlData = new ArrayList<XmlData>();
		XmlData xmlData = null;
		String m_searchTxt = "";
		try {
			m_searchTxt = URLEncoder.encode(searchTxt, "UTF8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			URL text = new URL("http://openapi.naver.com/search?key=" + key1 + "&query=" + m_searchTxt + "&display=" + count + "&start=1&target=local");
			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
			XmlPullParser parser = parserCreator.newPullParser();
			parser.setInput(text.openStream(), null);
			Log.i("NET", "Parsing...");
			int parseEvent = parser.getEventType();
			while (parseEvent != XmlPullParser.END_DOCUMENT) {
				switch (parseEvent) {
					case XmlPullParser.START_TAG:
						String tag = parser.getName();
						if (tag.compareTo("title") == 0) {
							xmlData = new XmlData();
							String titleSrc = parser.nextText();
							if (titleSrc.contains("<b>")) {
								titleSrc = titleSrc.replace("<b>", " ");
								titleSrc = titleSrc.replace("</b>", " ");
							}
							xmlData.d_title = titleSrc;
						}
						if (tag.compareTo("telephone") == 0) {
							String phoneSrc = parser.nextText();
							xmlData.d_phone = phoneSrc;
						}
						if (tag.compareTo("address") == 0) {
							String addressSrc = parser.nextText();
							xmlData.d_address = addressSrc;
						}
						if (tag.compareTo("mapx") == 0) {
							String mapxSrc = parser.nextText();
							xmlData.d_mapx = mapxSrc;
						}
						if (tag.compareTo("mapy") == 0) {
							String mapySrc = parser.nextText();
							xmlData.d_mapy = mapySrc;
							m_xmlData.add(xmlData);
						}
						break;
				}
				parseEvent = parser.next();
			}
			Log.i("NET", "End...");
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("NET", "Parsing Failed!");
		}
		return m_xmlData;
	}
}
